package com.linewow.xhyy.nihaonew.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.ChangeBounds;
import android.transition.Transition;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.linewow.xhyy.nihaonew.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by LXR on 2016/9/29.
 */
public class BeautyPhotoActivity extends AppCompatActivity {
    @Bind(R.id.photo_img)
    ImageView photoImg;
    @Bind(R.id.photo_toolbar)
    Toolbar photoToolbar;
    @Bind(R.id.photo_relative)
    RelativeLayout photoRelative;
    private String TAG="BeautyPhotoActivity";
    PhotoViewAttacher mPhotoViewAttacher;
    private String uri;
    private boolean mIsHidden;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_beauty_photo);
        ButterKnife.bind(this);
        initData();
        initView();
        photoToolbar.setAlpha(0.7f);
        if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP){
            getWindow().getSharedElementEnterTransition().addListener(mListener);
            getWindow().setSharedElementEnterTransition(new ChangeBounds());
        }

    }

    private Transition.TransitionListener mListener = new Transition.TransitionListener() {
        @Override
        public void onTransitionStart(Transition transition) {
            Log.e(TAG,"xingfeifei");
            photoRelative.animate()
                    .alpha(1f)
                    .setDuration(1000L)
                    .setInterpolator(new AccelerateInterpolator())
                    .start();
        }

        @Override
        public void onTransitionEnd(Transition transition) {

        }

        @Override
        public void onTransitionCancel(Transition transition) {

        }

        @Override
        public void onTransitionPause(Transition transition) {

        }

        @Override
        public void onTransitionResume(Transition transition) {

        }
    };

    private void setUpAttacher() {
        mPhotoViewAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
            @Override
            public void onViewTap(View view, float x, float y) {
                hideOrShowToolbar();
            }
        });
        mPhotoViewAttacher.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                new AlertDialog.Builder(BeautyPhotoActivity.this)
                        .setMessage("小猪 收了他")
                        .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface anInterface, int i) {
                                anInterface.dismiss();
                            }
                        })
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface anInterface, int i) {

                                anInterface.dismiss();
                                saveImage();
                            }
                        }).show();
                return false;
            }
        });
    }

    private void saveImage() {
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        File directory = new File(externalStorageDirectory,"LookLook");
        if (!directory.exists())
            directory.mkdir();
        Bitmap drawingCache = mPhotoViewAttacher.getImageView().getDrawingCache();
        try {
            File file = new File(directory, new Date().getTime() + ".jpg");
            FileOutputStream fos = new FileOutputStream(file);
            drawingCache.compress(Bitmap.CompressFormat.JPEG,100,fos);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            getApplicationContext().sendBroadcast(intent);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Snackbar.make(getCurrentFocus(),"阿偶出错了呢", Snackbar.LENGTH_SHORT).show();
        }
    }

    private void initView() {
        Picasso.with(this)
                .load(uri)
                .fit()
                .centerInside()
                .into(photoImg,imageLoadedCallback);
        photoToolbar.setNavigationIcon(R.drawable.ic_arrow_back);
        photoToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finishAnim();
            }
        });

    }




    private void finishAnim() {
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP){
            finishAfterTransition();
        }else{
            finish();
        }
    }

    private void initData() {
        uri=getIntent().getStringExtra("uri");
    }
    @Override
    protected void onResume() {
        super.onResume();
    }

    protected void hideOrShowToolbar() {
        photoToolbar.animate()
                .translationY(mIsHidden ? 0 : -photoToolbar.getHeight())
                .setInterpolator(new DecelerateInterpolator(2))
                .start();
        mIsHidden = !mIsHidden;
    }

    Callback imageLoadedCallback = new Callback() {

        @Override
        public void onSuccess() {
            if(mPhotoViewAttacher!=null){
                mPhotoViewAttacher.update();
            }else{
                mPhotoViewAttacher = new PhotoViewAttacher(photoImg);
                setUpAttacher();
            }
        }

        @Override
        public void onError() {
            // TODO Auto-generated method stub
        }
    };

}
